import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _list = List();
  ScrollController _scrollController;
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();
    _refresh();
    _scrollController = ScrollController()
      ..addListener(() {
        if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
          // 判断是否滑到底端，加载更多
          _loadMore();
        }
      });
  }

  Future<void> _refresh() async {
    await Future.delayed(Duration(seconds: 2), () {
      setState(() {
        _list = List.generate(Random().nextInt(20) + 15, (index) => 'item $index');
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("pull to refresh listview"),
      ),
      body: Center(
        child: RefreshIndicator(
          displacement: 20, // 下拉高度，默认40
          child: _list == null || _list.isEmpty
              ? Center(
                  child: CircularProgressIndicator(),
                )
              : ListView.builder(
                  controller: _scrollController,
                  itemCount: _list?.length,
                  itemBuilder: (context, index) {
                    if (index == _list.length - 1) {
                      return Center(
                        child: CircularProgressIndicator(),
                      );
                    } else {
                      return ListTile(
                        title: Text(_list[index]),
                      );
                    }
                  }),
          onRefresh: _refresh,
        ),
      ),
    );
  }

  Future<void> _loadMore() async {
    if (_isLoadingMore) {
      return;
    }
    print("load more");
    _isLoadingMore = true;
    await Future.delayed(Duration(milliseconds: 1500), () {
      setState(() {
        _list.addAll(List.generate(Random().nextInt(5) + 1, (index) => 'more item $index'));
        _isLoadingMore = false;
      });
    });
  }
}
